package com.hxgis.common.utils;

public class GridUtil {

    public static final double ininLon = 70d;

    public static final double ininLat = 15d;

    public static String getGridByLonAndLat(double lon, double lat){

        Integer x = new Integer(0);
        Integer y = new Integer(0);

        //横坐标
        if ((lat - ininLat) % 2 == 0 ){
            y = (int)(lat - ininLat) / 2;
        }else{
            y = (int)(Math.floor((lat - ininLat) / 2)) + 1;
        }

        //纵坐标
        if ((lon - ininLon) % 2 == 0 ){
            x = (int)(lon - ininLon) / 2;
        }else{
            x = (int)(Math.floor((lon - ininLon) / 2)) + 1;
        }

        return x + "," + y;
    }


    /**
     * 获取多边形形心
     * @param xs x坐标集合
     * @param ys y坐标集合
     * @return
     */
    public static double[] centroidOfPolygon(double[] xs,double[] ys){
        double[] centroid = new double[2];
        int n = xs.length;
        double area = 0f;
        double p = 0;
        for (int i = 0; i < n; i++) {
            if (i == (n - 1)) {
                area += 0.5f * (xs[i] * ys[0] - xs[0] * ys[i]);
            } else {
                area += 0.5f * (xs[i] * ys[i + 1] - xs[i + 1] * ys[i]);
            }
        }
        for (int i = 0; i < n; i++) {
            p = 1f / 6f / area;
            if (i == (n - 1)) {
                centroid[0] += p * (xs[i] + xs[0]) * (xs[i] * ys[0] - xs[0] * ys[i]);
                centroid[1] += p * (ys[i] + ys[0]) * (xs[i] * ys[0] - xs[0] * ys[i]);
            } else {
                centroid[0] += p * (xs[i] + xs[i + 1]) * (xs[i] * ys[i + 1] - xs[i + 1] * ys[i]);
                centroid[1] += p * (ys[i] + ys[i + 1]) * (xs[i] * ys[i + 1] - xs[i + 1] * ys[i]);
            }

        }

        return centroid;
    }



    public static void main(String[] args) {
        System.out.println(getGridByLonAndLat(78.36d, 17.63d));
        double[] doubles = centroidOfPolygon(new double[]{16.53d, 16.83d, 18.5, 18.8}, new double[]{111.62d, 112.33d, 110.03, 110.33});
        System.out.println(doubles[0] + "---" + doubles[1]);
    }


}
